package longshu.data.common.ds;

import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import java.lang.reflect.Method;

/**
 * TargetDSInterceptor
 *
 * @author LongShu 2018/01/27
 */
@Slf4j
public class TargetDSInterceptor implements MethodInterceptor {

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        // 获取目标数据源
        String target = getTarget(invocation);
        log.info("target:{}", target);
        DynamicDataSource.setDataSourceKey(target);

        try {
            return invocation.proceed();
        } finally {
            DynamicDataSource.clear();
        }
    }

    String getTarget(MethodInvocation invocation) {
        Method method = invocation.getMethod();
        Object thisObject = invocation.getThis();
        log.debug("method:{}", method);

        TargetDS targetDS;
        if (method.isAnnotationPresent(TargetDS.class)) {
            targetDS = method.getAnnotation(TargetDS.class);
            return targetDS.target();
        }

        if (thisObject != null && method.getDeclaringClass() == thisObject.getClass()) {
            targetDS = thisObject.getClass().getAnnotation(TargetDS.class);
        } else {
            targetDS = method.getDeclaringClass().getAnnotation(TargetDS.class);
        }
        if (targetDS != null) {
            return targetDS.target();
        }

        return null;
    }

}
